package com.zwj.interview.BFS;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * @Author: Zwj
 * @Date: 2023/2/2 14:36
 */
public class 二叉树后序遍历 {

    //后续遍历的顺序:左子树  右子树   根节点
    public List<Integer> postOrder(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        if (root == null) {
            return result;
        }
        //先将各节点压入栈中
        stack1.push(root);
        while (!stack1.isEmpty()) {
            //弹出stack1的节点，压入stack2
            TreeNode cur = stack1.pop();
            stack2.push(cur);
            //再将左右子树压入stack1
            if (cur.left != null) {
                stack1.push(cur.left);
            }
            if (cur.right != null) {
                stack1.push(cur.right);
            }
        }
        //最后遍历stack2中的数据
        while (!stack2.isEmpty()) {
            result.add(stack2.pop().val);
        }
        return result;
    }
}